package com.g7.dsp.util.testcase;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class BeanToExcel {
	private static WritableWorkbook wwb;
	private static WritableSheet ws;

	public static void transferXMLToExcel(String rawfilename) {
		String newfilename = null;
		try {
			newfilename = getExcelName(rawfilename, getNow());
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		System.out.println("newfilename:" + newfilename);
		System.out.println("converting,please wait...");
	}

	private static void writeExcelByLine(String newfilename, List<String> testcase) throws Exception {
		File file = new File(newfilename);

		if (!file.exists()) {
			try {
				wwb = Workbook.createWorkbook(file);
				ws = wwb.createSheet("TestCase", 0);
			} catch (IOException e) {
				e.printStackTrace();
			}

//			for (int i = 0; i < title.size(); i++) {
//				Label label0 = new Label(i, 0, (String) title.get(i));
//				Label label = new Label(i, 1, (String) testcase.get(i));
//				ws.addCell(label0);
//				ws.addCell(label);
//			}

			wwb.write();
			wwb.close();
		} else {
			Workbook twb = Workbook.getWorkbook(file);

			wwb = Workbook.createWorkbook(file, twb);

			ws = wwb.getSheet(0);

			int num = ws.getRows();
//			for (int i = 0; i < title.size(); i++) {
//				Label label = new Label(i, num, (String) testcase.get(i));
//				ws.addCell(label);
//			}

			wwb.write();
			wwb.close();
			twb.close();
		}
	}

	private static String getExcelName(String oldfilename, String time) {
		String newfilename = "";
		String[] temp = oldfilename.split("\\\\");
		String prename = temp[(temp.length - 1)].substring(0, temp[(temp.length - 1)].length() - 4);
		newfilename = oldfilename.substring(0, oldfilename.length() - temp[(temp.length - 1)].length()) + prename + "_"
				+ time + ".xls";

		return newfilename;
	}

	public static String getNow() throws ParseException {
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");
		return df.format(date).replace(" ", "");
	}

}
